package com.himiotech.core.framework.config.shiro.web.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.himiotech.core.framework.config.async.AsyncFactory;
import com.himiotech.core.framework.config.async.AsyncManager;
import com.himiotech.core.framework.helper.utils.ShiroUtils;
import com.himiotech.core.framework.helper.utils.SpringUtils;
import com.himiotech.core.project.model.entity.user.User;
import com.himiotech.core.project.service.impl.UserOnlineServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 退出过滤器
 *
 * @author ruoyi
 * @author wuwenbin
 */
@Slf4j
public class HimioLogoutFilter extends org.apache.shiro.web.filter.authc.LogoutFilter {
    /**
     * 退出后重定向的地址
     */
    private String loginUrl;

    public String getLoginUrl() {
        return loginUrl;
    }

    public void setLoginUrl(String loginUrl) {
        this.loginUrl = loginUrl;
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        try {
            Subject subject = getSubject(request, response);
            String redirectUrl = getRedirectUrl(request, response, subject);
            try {
                User user = ShiroUtils.getSysUser();
                if (ObjectUtil.isNotNull(user)) {
                    String loginName = user.getLoginName();
                    // 记录用户退出日志
                    AsyncManager.me().execute(AsyncFactory.recordLoginInfo(loginName, "logout", "退出成功"));
                    // 清理缓存
                    SpringUtils.getBean(UserOnlineServiceImpl.class).removeUserCache(loginName, ShiroUtils.getSessionId());
                }
                // 退出登录
                subject.logout();
            } catch (SessionException ise) {
                log.error("logout fail.", ise);
            }
            issueRedirect(request, response, redirectUrl);
        } catch (Exception e) {
            log.error("Encountered session exception during logout.  This can generally safely be ignored.", e);
        }
        return false;
    }

    /**
     * 退出跳转URL
     */
    @Override
    protected String getRedirectUrl(ServletRequest request, ServletResponse response, Subject subject) {
        String url = getLoginUrl();
        if (StrUtil.isNotEmpty(url)) {
            return url;
        }
        return super.getRedirectUrl(request, response, subject);
    }
}
